package com.fancy.learncenter.ui.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.WebView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.fancy.learncenter.R;
import com.fancy.learncenter.bean.APPVersionDataBean;
import com.fancy.learncenter.bean.ApkDecriptionBean;
import com.fancy.learncenter.bean.BaseBean;
import com.fancy.learncenter.bean.CartoonClassListBean;
import com.fancy.learncenter.bean.FFlibrarySystemTimeBean;
import com.fancy.learncenter.bean.LoginDataBean;
import com.fancy.learncenter.bean.TokenDataBean;
import com.fancy.learncenter.common.Constant;
import com.fancy.learncenter.common.LoginUserSharePrefernce;
import com.fancy.learncenter.common.MyApplication;
import com.fancy.learncenter.common.RSA;
import com.fancy.learncenter.common.StatusBarCompat;
import com.fancy.learncenter.net.CustomNetCallBack;
import com.fancy.learncenter.net.CustomNetSubscriber;
import com.fancy.learncenter.net.HttpMehtod;
import com.fancy.learncenter.ui.activity.base.BaseActivity;
import com.fancy.learncenter.ui.activity.base.MallCommonH5Activity;
import com.fancy.learncenter.ui.fragment.BookStoreFragment;
import com.fancy.learncenter.ui.fragment.MyselfFragment;
import com.fancy.learncenter.ui.fragment.NGKFragment;
import com.fancy.learncenter.ui.fragment.NewSchoolFragment;
import com.fancy.learncenter.ui.fragment.SchoolFragment;
import com.fancy.learncenter.ui.fragment.ShowFragment;
import com.fancy.learncenter.ui.view.UpdataAPKPopupWindow;
import com.fancy.learncenter.utils.LogUtil;
import com.fancy.learncenter.utils.NetUtil;
import com.fancy.learncenter.utils.SPUtils;
import com.fancy.learncenter.utils.ToastUtil;
import com.fancy.learncenter.utils.Utils;
import com.google.gson.Gson;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import ezy.boost.update.UpdateManager;
import okhttp3.ResponseBody;
import retrofit2.Response;
import rx.Subscriber;

public class MainActivity extends BaseActivity {

    FragmentManager fragmentManager;
    @Bind(R.id.fg_container)
    FrameLayout fgContainer;
    @Bind(R.id.bottom_img1)
    ImageView bottomImg1;
    @Bind(R.id.bottom_tv1)
    TextView bottomTv1;
    @Bind(R.id.bottom_ll1)
    LinearLayout bottomLl1;
    @Bind(R.id.bottom_img2)
    ImageView bottomImg2;
    @Bind(R.id.bottom_tv2)
    TextView bottomTv2;
    @Bind(R.id.bottom_ll2)
    LinearLayout bottomLl2;
    @Bind(R.id.bottom_img4)
    ImageView bottomImg4;
    @Bind(R.id.bottom_tv4)
    TextView bottomTv4;
    @Bind(R.id.bottom_ll4)
    LinearLayout bottomLl4;
    @Bind(R.id.bottom_img5)
    ImageView bottomImg5;
    @Bind(R.id.bottom_tv5)
    TextView bottomTv5;
    @Bind(R.id.bottom_ll5)
    LinearLayout bottomLl5;
    @Bind(R.id.bottom)
    LinearLayout bottom;

    //跳转MainAcitity Key
    public static String START_KEY = "start";

    /**
     * 跳转后的TYPE:
     */
    //NGK的TYPE
    public static int NGK_CODE = 103;
    //我的  我的活动
    public static int MY_ACTIVITY_CODE = 1051;
    //我的  我的订单
    public static int MY_ORDER_CODE = 1054;
    //我的  我的课程
    public static int MY_LESSON_CODE = 1054;

    public final static int CARTOON_SUDENT = 1056;


    boolean frceUpData = false;
    @Bind(R.id.mWebView)
    WebView mWebView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main, Status.STATUS);
        ButterKnife.bind(this);
        fragmentManager = getSupportFragmentManager();
        StatusBarCompat.compat(this, Color.parseColor("#0ED8B7"));

        bottomLl2.setVisibility(View.GONE);
//


        getSystemTime();
        getAPPCode();
        if (!TextUtils.isEmpty(LoginUserSharePrefernce.getMobile()) && !TextUtils.isEmpty(LoginUserSharePrefernce.getPassword())) {
            JPushInterface.setAlias(this, 1, LoginUserSharePrefernce.getMobile());
            getToken();
        } else {
            showIndex(4);
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        LogUtil.MyLog("onResume", SPUtils.gettStudentRole() + "======MainActivity==确认=======" + SPUtils.gettTeacherRole());
    }

    private ShowFragment showFragment;
    private BookStoreFragment bookStoreFragment;
    private NewSchoolFragment schoolFragment;
    private MyselfFragment myselfFragment;

    Fragment tempFrag;
    FragmentTransaction transaction;

    private void showIndex(int index) {
        if (oldPLocation == index) {
            return;
        }

        transaction = fragmentManager.beginTransaction();
        switch (index) {
            case 1:
                showBottomGround(index);
                if (showFragment == null) {
                    showFragment = new ShowFragment();
                    transaction.add(R.id.fg_container, showFragment);
                }

                if (tempFrag == null) {
                    tempFrag = showFragment;
                }

                transaction.hide(tempFrag);
                transaction.show(showFragment);
                transaction.commit();
                tempFrag = showFragment;

                break;
            case 2:
                showBottomGround(index);
                if (bookStoreFragment == null) {
                    bookStoreFragment = new BookStoreFragment();
                    transaction.add(R.id.fg_container, bookStoreFragment);
                }

                if (tempFrag == null) {
                    tempFrag = bookStoreFragment;
                }

                transaction.hide(tempFrag);
                transaction.show(bookStoreFragment);
                transaction.commit();
                tempFrag = bookStoreFragment;
                break;
            case 4:
                showBottomGround(index);
                transaction = fragmentManager.beginTransaction();
                if (schoolFragment == null) {
                    schoolFragment = new NewSchoolFragment();
                    transaction.add(R.id.fg_container, schoolFragment);
                }


                if (tempFrag == null) {
                    tempFrag = schoolFragment;
                }

                transaction.hide(tempFrag);
                transaction.show(schoolFragment);
                transaction.commit();
                tempFrag = schoolFragment;

                break;
            case 5:
                showBottomGround(index);
                transaction = getSupportFragmentManager().beginTransaction();
                if (myselfFragment == null) {
                    myselfFragment = new MyselfFragment();
                    transaction.add(R.id.fg_container, myselfFragment);
                }

                if (tempFrag == null) {
                    tempFrag = myselfFragment;
                }
                transaction.hide(tempFrag);
                transaction.show(myselfFragment);
                transaction.commit();
                tempFrag = myselfFragment;
                break;
        }
    }

    private int oldPLocation = 0;

    private void showBottomGround(int dex) {

        switch (oldPLocation) {
            case 1:
                bottomImg1.setImageResource(R.mipmap.show_new_icon);
                bottomTv1.setTextColor(getResources().getColor(R.color.main_bottom_text_color));
                break;
            case 2:
                bottomImg2.setImageResource(R.mipmap.bookstore_icon);
                bottomTv2.setTextColor(getResources().getColor(R.color.main_bottom_text_color));
                break;
            case 4:
                bottomImg4.setImageResource(R.mipmap.school_icon);
                bottomTv4.setTextColor(getResources().getColor(R.color.main_bottom_text_color));
                break;
            case 5:
                bottomImg5.setImageResource(R.mipmap.myself_icon);
                bottomTv5.setTextColor(getResources().getColor(R.color.main_bottom_text_color));
                break;
        }


        switch (dex) {
            case 1:
                bottomImg1.setImageResource(R.mipmap.show_pressed_icon);
                bottomTv1.setTextColor(getResources().getColor(R.color.main_bottom_text_pressed_color));
                break;
            case 2:
                bottomImg2.setImageResource(R.mipmap.bookstore_pressed_icon);
                bottomTv2.setTextColor(getResources().getColor(R.color.main_bottom_text_pressed_color));
                break;
            case 4:
                bottomImg4.setImageResource(R.mipmap.school_pressed_icon);
                bottomTv4.setTextColor(getResources().getColor(R.color.main_bottom_text_pressed_color));
                break;
            case 5:
                bottomImg5.setImageResource(R.mipmap.myself_pressed_icon);
                bottomTv5.setTextColor(getResources().getColor(R.color.main_bottom_text_pressed_color));
                break;
        }

        oldPLocation = dex;
    }


    @OnClick({R.id.bottom_ll1, R.id.bottom_ll2, R.id.bottom_ll4, R.id.bottom_ll5})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bottom_ll1:
                showIndex(1);
                break;
            case R.id.bottom_ll2:
//                showIndex(2);
                break;
            case R.id.bottom_ll4:

                if (Constant.isLogin) {


                    if (SPUtils.gettTeacherRole()) {
                        showIndex(4);
                    } else if (SPUtils.gettStudentRole()) {

                        if (!TextUtils.isEmpty(SPUtils.getClassID())) {
                            MyApplication.classIDStr = SPUtils.getClassID().split(",")[0];
                            MyApplication.classNameStr = SPUtils.getClassID().split(",")[1];

                            Intent intent = new Intent(MainActivity.this, CartoonChildHomeActivity.class);
                            startActivity(intent);
                        } else {
                            showIndex(4);
//                            getClassList();
                        }

                    } else {
                        showIndex(4);
                    }
                } else {
                    Intent intent = new Intent(this, LoginActivity.class);
                    startActivity(intent);
                }


                break;
            case R.id.bottom_ll5:
                if (Constant.isLogin) {
                    showIndex(5);
                } else {
                    Intent intent = new Intent(this, LoginActivity.class);
                    startActivity(intent);
                }
                break;
        }
    }


    private void getSystemTime() {
        Map<String, String> valueData = new HashMap<>();
        String currentTime = String.valueOf(System.currentTimeMillis() / 1000);
        valueData.put("time", currentTime);


        HttpMehtod.getInstance().getFFlibrarySystemTime(new Subscriber<Response<ResponseBody>>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(Response<ResponseBody> o) {

                String result = NetUtil.getResResult(o);
                Gson gson = new Gson();
                FFlibrarySystemTimeBean bean = gson.fromJson(result, FFlibrarySystemTimeBean.class);
                long dValue = bean.getResult() - Utils.getCurrentTime();
                LoginUserSharePrefernce.setTime(dValue);


            }
        }, valueData);

    }


    private void getToken() {
        HttpMehtod.getInstance().getToken(new CustomNetSubscriber(this) {

            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {
                //解析数据
                BaseBean<TokenDataBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), TokenDataBean.class);
                //数据业务逻辑处理
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<TokenDataBean>() {
                    @Override
                    public void success(TokenDataBean dataBean) {
                        Constant.loginToken = dataBean.getLoginToken();
                        Constant.JSESSIONID = dataBean.getJSESSIONID();

                        if (SPUtils.gettTeacherRole()) {
                            showIndex(4);
                        } else if (SPUtils.gettStudentRole() && !TextUtils.isEmpty(SPUtils.getClassID())) {
                            MyApplication.classIDStr = SPUtils.getClassID().split(",")[0];
                            MyApplication.classNameStr = SPUtils.getClassID().split(",")[1];

                            Intent intent = new Intent(MainActivity.this, CartoonChildHomeActivity.class);
                            startActivityForResult(intent, CARTOON_SUDENT);
                        } else {
                            showIndex(4);
                        }

                        login(LoginUserSharePrefernce.getMobile(), LoginUserSharePrefernce.getPassword());

                    }

                    @Override
                    public void fail(String errorCode) {

                    }
                }).customDealData();
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == CARTOON_SUDENT) {
            switch (resultCode) {
                case CARTOON_SUDENT:
                    showIndex(1);
                    break;
            }
        } else {
            if (resultCode == Constant.FRESH_RESULT_CALLBACK) {
                showIndex(1);
            }

        }


    }


    private void getAPPCode() {
        Map map = new HashMap();
        map.put("mobileVersion", Utils.getVersionName());
        map.put("appIdentify", Constant.KEY_FR0M);
        map.put("platform", "1");
        HttpMehtod.getInstance().getAPPVersion(map, new CustomNetSubscriber(this) {

            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {
                //解析数据
                BaseBean<APPVersionDataBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), APPVersionDataBean.class);
                //数据业务逻辑处理
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<APPVersionDataBean>() {
                    @Override
                    public void success(APPVersionDataBean dataBean) {

                        if (dataBean.getVersionVO() != null) {
                            String url = "http://a.app.qq.com/o/simple.jsp?pkgname=com.fancy.learncenter";
                            String desc = "";
//                            if (dataBean.getVersionVO().getContent() != null) {
//
//                                Gson gson = new Gson();
//                                ApkDecriptionBean decriptionBean = gson.fromJson(dataBean.getVersionVO().getContent(), ApkDecriptionBean.class);
//                                desc = decriptionBean.getDes();
//                                url = decriptionBean.getUrl();
//                            }
                            updataAPKPopupWindow = new UpdataAPKPopupWindow(getContext(), fgContainer, dataBean.getVersionVO().getTitle(), dataBean.getVersionVO().getContent(), url);
                            if (dataBean.getVersionVO().getUpdateState() == 1) {
                                updataAPKPopupWindow.showPopupWindow();
                            } else if (dataBean.getVersionVO().getUpdateState() == 2) {
                                frceUpData = true;
                                updataAPKPopupWindow.setCloseHide();
                                updataAPKPopupWindow.showPopupWindow();
                            }
                        }
                    }

                    @Override
                    public void fail(String errorCode) {

                    }
                }).customDealData();
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
            }
        });
    }

    UpdataAPKPopupWindow updataAPKPopupWindow;

    private void login(String mobile, final String password) {

        String rsaStr = "";
        try {
            rsaStr = RSA.ecrypt(Constant.loginToken + password, Constant.RSA_PUBLIC_KEY, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map map = new HashMap();
        map.put("password", rsaStr);
        map.put("mobile", mobile);
        HttpMehtod.getInstance().login(map, new CustomNetSubscriber(this) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {

                //解析数据
                BaseBean<LoginDataBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), LoginDataBean.class);
                //数据业务逻辑处理
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<LoginDataBean>() {
                    @Override
                    public void success(LoginDataBean dataBean) {
                        Constant.isLogin = true;

                        LoginUserSharePrefernce.putCustomId(dataBean.getLoginUser().getCustomerId());
                        LoginUserSharePrefernce.putHeaderPath(dataBean.getLoginUser().getHeaderImageUrl());
                        LoginUserSharePrefernce.putMobile(dataBean.getLoginUser().getMobile());
                        LoginUserSharePrefernce.putPassword(password);
                        LoginUserSharePrefernce.putName(dataBean.getLoginUser().getNickname());
                        LoginUserSharePrefernce.putFid(dataBean.getLoginUser().getFancyId());
                        LoginUserSharePrefernce.putToken(dataBean.getLoginUser().getToken());
                        LoginUserSharePrefernce.update(true);
                        LoginUserSharePrefernce.login(true);

                        LoginMall();
                    }

                    @Override
                    public void fail(String errorCode) {
                        LoginUserSharePrefernce.login(false);
                    }

                }).customDealData();

            }
        });
    }

    //商城登录
    private void LoginMall() {
        String url = Constant.getMallLoginUrl();
        String fid = LoginUserSharePrefernce.getFid();
        String token = LoginUserSharePrefernce.getToken();

        StringBuilder sbUrl = new StringBuilder();
        sbUrl.append(url);
        try {
            sbUrl.append("&fid=").append(fid)
                    .append("&token=").append(token)
                    .append("&location=").append(URLEncoder.encode("无城市", "utf-8"))
                    //用户看到的版本号
                    .append("&userVs=").append(Utils.getVersionName())
                    // 手机更新迭代次数
                    .append("&developVs=").append(Utils.getVersionCode())
                    .append("&pushToken=").append(URLEncoder.encode("无参数", "utf-8"))
                    //   操作系统
                    .append("&os=").append("Android")
                    //   系统版本号
                    .append("&osVs=").append(Build.VERSION.RELEASE)
                    //   手机型号
                    .append("&deviceType=").append(Build.MODEL)
                    //   手机唯一识别码
                    .append("&deviceUtdid=").append(URLEncoder.encode("无参数", "utf-8"))
                    .append("&fromApp=").append(URLEncoder.encode("环球少年", "utf-8"));

        } catch (Exception e) {
            e.printStackTrace();
        }

        CookieManager cookieManager = CookieManager.getInstance();
        String CookieStr = cookieManager.getCookie(sbUrl.toString());
        cookieManager.removeAllCookie();

        mWebView.loadUrl(sbUrl.toString());
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Intent newIntent;
        if (intent.getIntExtra(START_KEY, 0) == MY_ACTIVITY_CODE) {
            showIndex(1);

            newIntent = new Intent(this, MallCommonH5Activity.class);
            newIntent.putExtra(MallCommonH5Activity.URL_KEY, Constant.getMallActivity());
            startActivity(newIntent);
        } else if (intent.getIntExtra(START_KEY, 0) == MY_LESSON_CODE) {
            showIndex(1);

            newIntent = new Intent(this, MallCommonH5Activity.class);
            newIntent.putExtra(MallCommonH5Activity.URL_KEY, Constant.getMyLesson());
            startActivity(newIntent);
        } else if (intent.getIntExtra(START_KEY, 0) == MY_ORDER_CODE) {
            showIndex(1);
            newIntent = new Intent(this, MallCommonH5Activity.class);
            newIntent.putExtra(MallCommonH5Activity.URL_KEY, Constant.getMallOrder());
            startActivity(newIntent);

        } else if (intent.getIntExtra(START_KEY, 0) == NGK_CODE) {

            showIndex(1);
        } else if (intent.getIntExtra(START_KEY, 0) == CARTOON_SUDENT) {
            showIndex(1);
        }
    }

    private long mExitTime;

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            if (frceUpData) {
                return true;
            }
            if (updataAPKPopupWindow != null && updataAPKPopupWindow.isShowing()) {
                updataAPKPopupWindow.dismiss();
                return true;
            }
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                ToastUtil.show("连续点击两次退出程序");
                mExitTime = System.currentTimeMillis();
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    private void getClassList() {
        Map<String, Object> map = new HashMap<>();
        HttpMehtod.getInstance().cartoonListOfClass(map, new CustomNetSubscriber(this, true) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {

                BaseBean<CartoonClassListBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), CartoonClassListBean.class);
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<CartoonClassListBean>() {
                    @Override
                    public void success(CartoonClassListBean dataBean) {

                        if (dataBean.getResult() != null && dataBean.getResult().size() > 0) {
                            MyApplication.classNameStr = dataBean.getResult().get(0).getClassName();
                            MyApplication.classIDStr = dataBean.getResult().get(0).getClassId() + "";
                            SPUtils.putClassID(MyApplication.classIDStr + "," + MyApplication.classNameStr);


                            LogUtil.MyLog("putStudentRole", "======getClassList======");
                            SPUtils.putStudentRole(true);
                            SPUtils.putTeacherRole(false);

                            Intent intent = new Intent(MainActivity.this, CartoonChildHomeActivity.class);
                            startActivity(intent);
                        } else {
                            LogUtil.MyLog("CartoonClassListBean", "=======CartoonClassListBean===");
                        }
                    }

                    @Override
                    public void fail(String errorCode) {

                    }


                }).dealData();
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
            }
        });

    }

}
